package threadlocal;

/**
 * @Classname ThreadLocalNPE
 * @Description ThreadLocal空指针异常
 * @Date 2024/1/14 23:45
 * @Author zhuzhenguo
 */
public class ThreadLocalNPE {
    ThreadLocal<Long> longThreadLocal = new ThreadLocal<Long>();

    public void set() {
        longThreadLocal.set(Thread.currentThread().getId());
    }

    /**
     * Long就会做一个自动拆箱转为long，就会报空指针异常
     *
     * @return long
     */
    public long get() {
        return longThreadLocal.get();
    }

    public static void main(String[] args) {
        ThreadLocalNPE threadLocalNPE = new ThreadLocalNPE();
        // 没有设置初值就直接get
        // 返回值是一个包装类型
        System.out.println(threadLocalNPE.get());
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocalNPE.set();
                System.out.println(threadLocalNPE.get());
            }
        });
        thread1.start();
    }
}
